package com.example.zhihuhelpapp;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.zhihuhelpapp.activity.InputJingDongKeyActivity;
import com.example.zhihuhelpapp.activity.InputQuestionOrAnswerUrlActivity;
import com.example.zhihuhelpapp.activity.OrderListActivity;
import com.example.zhihuhelpapp.activity.QuestionListActivity;
import com.example.zhihuhelpapp.activity.SetNickNameActivity;
import com.example.zhihuhelpapp.api.MySubscribe;
import com.example.zhihuhelpapp.base.MyBaseRxActivity;
import com.example.zhihuhelpapp.bean.QuestionBean;
import com.example.zhihuhelpapp.bean.QuestionResultBean;
import com.example.zhihuhelpapp.configs.ConfigInfoActivity;
import com.example.zhihuhelpapp.excel.LoadExcelDataActivity;
import com.example.zhihuhelpapp.mvp.MainPresenter;
import com.example.zhihuhelpapp.mvp.QuestionListPresenter;
import com.example.zhihuhelpapp.mvp.contract.IMainContract;
import com.example.zhihuhelpapp.mvp.contract.IQuestionListContract;
import com.example.zhihuhelpapp.service.JingDongService;
import com.example.zhihuhelpapp.utils.CoreConstant;
import com.example.zhihuhelpapp.utils.DialogUtils;
import com.example.zhihuhelpapp.utils.SpUtils;
import com.example.zhihuhelpapp.utils.UIUtils;
import com.example.zhihuhelpapp.utils.rxpermission.RxPermissions;
import com.pgyersdk.update.PgyUpdateManager;
import com.tencent.mmkv.MMKV;

import java.util.List;
import java.util.Random;

public class MainActivity extends MyBaseRxActivity<MainPresenter>
        implements IMainContract.IView, IQuestionListContract.IView {
    private QuestionListPresenter questionListPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        showToolBar(false, getString(R.string.page_home));
    }

    @Override
    protected void initData() {
        super.initData();
        questionListPresenter = new QuestionListPresenter();
        questionListPresenter.attachView(this);

        // 检测更新
        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            DialogUtils.showDialog(this, getString(R.string.tip),
                    getString(R.string.tip_request_read_storage_permission), (dialog, which) -> checkUpdate());
        } else {
            checkUpdate();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.checkPageContent(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void checkUpdate() {
        new RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new MySubscribe<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        // 检测更新
                        new PgyUpdateManager.Builder()
                                .setForced(false)                //设置是否强制更新
                                .setUserCanRetry(false)         //失败后是否提示重新下载
                                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk
                                .register();

                    }
                });
    }

    public void goInstructions(View view) {
        DialogUtils.showDialog(this, getString(R.string.app_user_guideline),
                getString(R.string.user_instructions),
                (dialog, which) -> dialog.dismiss());
    }

    public void goQuestionList(View view) {
        startActivity(new Intent(this, QuestionListActivity.class));
    }

    public void goSetNickName(View view) {
        startActivity(new Intent(this, SetNickNameActivity.class));
    }

    public void inputByUser(View view) {
        startActivity(new Intent(this, InputQuestionOrAnswerUrlActivity.class));
    }

    public void getOrderList(View view) {
        String appKey = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_JD_APP_KEY, "");
        String appSecret = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_JD_APP_SECRET, "");
        if (TextUtils.isEmpty(appKey) || TextUtils.isEmpty(appSecret)) {
            DialogUtils.showDialog(this, getString(R.string.tip), getString(R.string.input_jd_need_key_tip),
                    (dialog, which) -> startActivity(new Intent(MainActivity.this, InputJingDongKeyActivity.class)));
        } else {
            startActivity(new Intent(this, OrderListActivity.class));
        }
    }

    public void startJDService(View view) {
        String appKey = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_JD_APP_KEY, "");
        String appSecret = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_JD_APP_SECRET, "");
        if (TextUtils.isEmpty(appKey) || TextUtils.isEmpty(appSecret)) {
            DialogUtils.showDialog(this, getString(R.string.tip), getString(R.string.input_jd_need_key_tip),
                    (dialog, which) -> startActivity(new Intent(MainActivity.this, InputJingDongKeyActivity.class)));
        } else {
            DialogUtils.showDialog(this, getString(R.string.tip), getString(R.string.start_jd_service_tip),
                    (dialog, which) -> {
                        Intent intent = new Intent(MainActivity.this, JingDongService.class);
                        // Android 8.0使用startForegroundService在前台启动新服务
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            MainActivity.this.startForegroundService(intent);
                        } else {
                            MainActivity.this.startService(intent);
                        }
                    });
        }
    }

    public void importExcelData(View view){
        startActivity(new Intent(this, LoadExcelDataActivity.class));
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public void onGetLocalQuestionList(List<QuestionBean> questionBeanList) {

    }

    @Override
    public void onSaveQuestionSuccess() {
        UIUtils.showToast(R.string.save_success);
        startActivity(new Intent(this, QuestionListActivity.class));
    }

    @Override
    public void onDelQuestionSuccess() {
        UIUtils.showToast(R.string.del_success);
    }

    @Override
    public void onNewQuestion(String questionId) {
        questionListPresenter.getQuestionDetail(questionId, 0);
    }

    @Override
    public void onNewAnswer(String answerId) {
        questionListPresenter.getAnswerDetail(answerId);
    }

    @Override
    public void onGetQuestionDetail(QuestionResultBean resultBean) {
        if (resultBean != null) {
            List<QuestionResultBean.DataBean> dataList = resultBean.getData();
            QuestionBean questionBean = new QuestionBean();
            questionBean.setQuestionAnswerCount(resultBean.getPaging().getTotals());
            if (dataList != null && dataList.size() > 0) {
                QuestionResultBean.DataBean dataBean = dataList.get(0);
                QuestionResultBean.DataBean.QuestionBean question = dataBean.getQuestion();
                questionBean.setQuestionId(String.valueOf(question.getId()));
                questionBean.setQuestionTitle(question.getTitle());
            }
            questionBean.setUpdateTime(System.currentTimeMillis());
            questionListPresenter.saveQuestionToLocal(questionBean);
        }
    }

}
